package com.mfw.springboot.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mfw.springboot.annotation.AuthCheck;
import com.mfw.springboot.common.BaseResponse;
import com.mfw.springboot.common.DataGroupByDateDTO;
import com.mfw.springboot.common.DeleteRequest;
import com.mfw.springboot.common.ErrorCode;
import com.mfw.springboot.common.Result;
import com.mfw.springboot.constant.UserConstant;
import com.mfw.springboot.exception.BusinessException;
import com.mfw.springboot.exception.ThrowUtils;
import com.mfw.springboot.model.dto.classInfo.ClassInfoAddRequest;
import com.mfw.springboot.model.dto.classInfo.ClassInfoEditRequest;
import com.mfw.springboot.model.dto.classInfo.ClassInfoQueryRequest;
import com.mfw.springboot.model.dto.classInfo.ClassInfoUpdateRequest;
import com.mfw.springboot.model.entity.ClassInfo;
import com.mfw.springboot.model.entity.User;
import com.mfw.springboot.model.vo.ClassInfoVO;
import com.mfw.springboot.service.ClassInfoService;
import com.mfw.springboot.service.UserService;
import com.mfw.springboot.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 班级接口
 *
 * @author mfw
 * @from <a href="https://gitee.com/hanhuaifei/projects">我的gitee</a>
 * @Date 2024/9/26
 */
@RestController
@RequestMapping("/classInfo")
@Slf4j
public class ClassInfoController {

    @Resource
    private ClassInfoService classInfoService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建班级
     *
     * @param classInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addClassInfo(@RequestBody ClassInfoAddRequest classInfoAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(classInfoAddRequest == null, ErrorCode.PARAMS_ERROR);
        // 在此处将实体类和 DTO 进行转换
        ClassInfo classInfo = new ClassInfo();
        BeanUtils.copyProperties(classInfoAddRequest, classInfo);
        // 数据校验
        classInfoService.validClassInfo(classInfo, true);
        // 填充默认值
        User loginUser = userService.getLoginUser(request);
        classInfo.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = classInfoService.save(classInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newClassInfoId = classInfo.getId();
        return Result.success(newClassInfoId);
    }

    /**
     * 删除班级
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteClassInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        ClassInfo oldClassInfo = classInfoService.getById(id);
        ThrowUtils.throwIf(oldClassInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldClassInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = classInfoService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 更新班级（仅管理员可用）
     *
     * @param classInfoUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateClassInfo(@RequestBody ClassInfoUpdateRequest classInfoUpdateRequest) {
        if (classInfoUpdateRequest == null || classInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        ClassInfo classInfo = new ClassInfo();
        BeanUtils.copyProperties(classInfoUpdateRequest, classInfo);
        // 数据校验
        classInfoService.validClassInfo(classInfo, false);
        // 判断是否存在
        long id = classInfoUpdateRequest.getId();
        ClassInfo oldClassInfo = classInfoService.getById(id);
        ThrowUtils.throwIf(oldClassInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = classInfoService.updateById(classInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 根据 id 获取班级（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ClassInfoVO> getClassInfoVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        ClassInfo classInfo = classInfoService.getById(id);
        ThrowUtils.throwIf(classInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return Result.success(classInfoService.getClassInfoVO(classInfo, request));
    }

    /**
     * 分页获取班级列表（仅管理员可用）
     *
     * @param classInfoQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<ClassInfo>> listClassInfoByPage(@RequestBody ClassInfoQueryRequest classInfoQueryRequest) {
        long current = classInfoQueryRequest.getCurrent();
        long size = classInfoQueryRequest.getPageSize();
        // 查询数据库
        Page<ClassInfo> classInfoPage = classInfoService.page(new Page<>(current, size),
                classInfoService.getQueryWrapper(classInfoQueryRequest));
        return Result.success(classInfoPage);
    }

    /**
     * 分页获取班级列表（封装类）
     *
     * @param classInfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ClassInfoVO>> listClassInfoVOByPage(@RequestBody ClassInfoQueryRequest classInfoQueryRequest,
                                                               HttpServletRequest request) {
        long current = classInfoQueryRequest.getCurrent();
        long size = classInfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<ClassInfo> classInfoPage = classInfoService.page(new Page<>(current, size),
                classInfoService.getQueryWrapper(classInfoQueryRequest));
        // 获取封装类
        return Result.success(classInfoService.getClassInfoVOPage(classInfoPage, request));
    }

    /**
     * 分页获取当前登录用户创建的班级列表
     *
     * @param classInfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<ClassInfoVO>> listMyClassInfoVOByPage(@RequestBody ClassInfoQueryRequest classInfoQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(classInfoQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        classInfoQueryRequest.setUserId(loginUser.getId());
        long current = classInfoQueryRequest.getCurrent();
        long size = classInfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<ClassInfo> classInfoPage = classInfoService.page(new Page<>(current, size),
                classInfoService.getQueryWrapper(classInfoQueryRequest));
        // 获取封装类
        return Result.success(classInfoService.getClassInfoVOPage(classInfoPage, request));
    }

    /**
     * 编辑班级（给用户使用）
     *
     * @param classInfoEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editClassInfo(@RequestBody ClassInfoEditRequest classInfoEditRequest, HttpServletRequest request) {
        if (classInfoEditRequest == null || classInfoEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        ClassInfo classInfo = new ClassInfo();
        BeanUtils.copyProperties(classInfoEditRequest, classInfo);
        // 数据校验
        classInfoService.validClassInfo(classInfo, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = classInfoEditRequest.getId();
        ClassInfo oldClassInfo = classInfoService.getById(id);
        ThrowUtils.throwIf(oldClassInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldClassInfo.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = classInfoService.updateById(classInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
    * 日新增统计班级
    *
    * @return
    */
    @PostMapping("/day/newly/added")
    public BaseResponse<List<DataGroupByDateDTO>> dayNewlyAddedClassInfo() {
        // 今天
        Date endDate = DateUtils.getNow();
        // 30天以前
        Date beginDate = DateUtils.dayAfter(endDate, -30);
        // 查询
        List<DataGroupByDateDTO> classInfoDataList = classInfoService.countByDay(beginDate, endDate);
        //返回结果
        return Result.success(classInfoDataList);

    }

    // endregion
}
